<!-- 任务执行情况 -->
<template>
  <el-dialog title="视频采集" :visible.sync="dialogVisible" @close="$emit('update:visible',false)"
             :close-on-click-modal="false" width="80%" top="50px">
    <div>
      <div class="camera_outer">
        <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
        <canvas style="display:none;" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>
        <!--        <div v-if="imgSrc" class="img_bg_camera">-->
        <!--          <img :src="imgSrc" alt="" class="tx_img">-->
        <!--        </div>-->
        <!--        <button @click="getCompetence()">打开摄像头</button>-->
        <!--        <button @click="stopNavigator()">关闭摄像头</button>-->
        <!--        <button @click="setImage()">拍照</button>-->
      </div>
      <!--      采集组件-->
      <div class="video-urlbox">
        <div class="video-timeNumber">
          <vue-record-video mode="press"
                            @stream="onVideoStream"
                            @result="onResult"
                            style="width:100px;"
                            v-if="dialogVisible"
                            @mousedown="startRecording"
                            @mouseleave="stopRecording"
                            @mouseup="stopRecording"
                            @touchstart="startRecording"
                            @touchend="stopRecording"
                            @touchcancel="stopRecording"/>
          <div class="video-timeNumber-index" v-if="showtime">时长：{{ videoTime }}</div>
        </div>
        <video ref="VideoBox" width="400" height="250" controls v-show="videoSrc" id="videoshowBox"></video>
      </div>
      <div class="mt-20">
        <el-input
            type="input"
            :rows="2"
            placeholder="备注"
            v-model="textarea"
            class="textareaBox">
        </el-input>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('update:visible',false)" size="small">返回</el-button>
      <el-button type="primary" @click="onSubmitFn" size="small">确认并提交保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {Loading} from 'element-ui' // 项目已经全局引入element的话可以不单独引入
export default {
  name: 'video',
  props: ['visible', 'cornerVideoId'],
  components: {},
  data() {
    return {
      dialogVisible: this.visible,
      videoWidth: 800,
      videoHeight: 600,
      imgSrc: '',
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      recorder: null,
      videoSrc: false,
      showtime: false,
      videoTime: 0,
      timeNumberFn: null,
      videoSrcOption: '',
      loading: null,
      textarea:'',
      videoStatus: true
    }
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible
      if (this.visible) {
        console.log(this.visible,this.cornerVideoId)
        let n = this;
        setTimeout(() => {
          n.getCompetence()
        }, 500)
      } else {
        console.log('close')
        clearInterval(this.timeNumberFn)
        this.showtime = false;
        this.videoTime =0;
        this.videoSrc = false
        this.stopNavigator();
      }
    }
  },
  created() {
  },
  methods: {
    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this
      // this.thisCancas = document.getElementById('canvasCamera')
      // this.thisContext = this.thisCancas.getContext('2d')
      this.thisVideo = document.getElementById('videoCamera')
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      var constraints = {
        audio: false,
        video: {width: this.videoWidth, height: this.videoHeight, transform: 'scaleX(-1)'}
      }
      navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // 旧的浏览器可能没有srcObject
        if ('srcObject' in _this.thisVideo) {
          _this.thisVideo.srcObject = stream
        } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
          _this.thisVideo.src = window.URL.createObjectURL(stream)
        }
        _this.thisVideo.onloadedmetadata = function (e) {
          _this.thisVideo.play()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 录制视频，结束了
    onResult(data) {
      console.log('The blob data:', data);
      console.log('Downloadable audio', window.URL.createObjectURL(data));
      this.videoSrcOption = data
      clearInterval(this.timeNumberFn)
      this.videoSrc = true
      this.$refs.VideoBox.srcObject = null
      this.$refs.VideoBox.src = window.URL.createObjectURL(data)
      this.videoSrc = window.URL.createObjectURL(data)
    },
    // 开始录制
    onVideoStream(stream) {
      this.videoSrc = false
      this.videoTime = 0
      this.showtime = true
      let n = this
      this.$refs.VideoBox.srcObject = null
      this.$refs.VideoBox.src = ''
      this.timeNumberFn = setInterval(() => {
        n.videoTime++
      }, 1000)
      console.log('Got a video stream object:', stream);
    },
    // @mousedown="startRecording"
    // @mouseleave="stopRecording"
    // @mouseup="stopRecording"
    // @touchstart="startRecording"
    // @touchend="stopRecording"
    // @touchcancel="stopRecording"
    startRecording(){
      console.log('startRecording')
    },
    stopRecording(){
      console.log('stopRecording')
    },
    // 绘制图片（拍照功能）
    setImage() {
      var _this = this
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, _this.videoWidth, _this.videoHeight)
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL('image/jpg')
      _this.imgSrc = image
    },

    // base64转文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, {type: mime})
    },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop()
    },
    // 保存视频
    onSubmitFn() {
      let n = this
      if (!this.videoSrcOption) {
        this.$message.error('请录制视频')
        return
      }
      this.loading = Loading.service({
        lock: true,
        text: '保存中…',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.4)',
        customClass: 'fontColor'
      })
      const formData = new FormData();
      formData.append("file", this.videoSrcOption, 'cornerVideo.mp4');
      console.log('formData:', formData)
      // formData.append("token",sessionStorage.getItem("token"))
      //'http://120.78.228.13' + this.api.upload_img
      this.axios
          .post('upload/oldupload', formData)
          .then(response => {
            console.log('图片回执：', response)
            if (!response.data.code) {
              var vide = document.getElementById("videoshowBox");
              vide.pause();
              this.saveVideoOptionFn(response.data.data.name)
            }
          })
          .catch(response => {
          })
    },
    // 提交数据内容
    async saveVideoOptionFn(videoSrc) {
      console.log('videoSrc:',videoSrc)
      let n = this;
      // corner_id 区角id video 视频地址
      let {data} = await this.$post(this.api.corner.video.add, {corner_id:this.cornerVideoId,video:videoSrc,remark:this.textarea}); //类型0游客1家长2老师
      console.log(data)
      this.videoSrc = false
      this.$refs.VideoBox.srcObject = null
      this.videoTime = 0
      n.$message.success('提交成功')
      this.loading.close()
    }
  },
  mounted() {
    console.log('获取按键视频')
    let n = this;
    setTimeout(() => {
      n.getCompetence()
    }, 500)

  }
}
</script>
<style scoped>
.camera_outer {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.video-urlbox {
  display: flex;
  align-items: center;
  justify-content: center;
}
.textareaBox textarea{
  height: 70px;
}
</style>
